﻿using MyIServices;
using MyModels.Models;
using MyServices.BASE;
using SqlSugar.Extensions;

namespace MyServices
{
    public class UserRoleService : BaseService<UserRole>, IUserRoleService
    {
        public async Task<long> GetRoleIdByUserId(long userId)
        {
            var role = (await Query(i => i.UserId == userId)).OrderByDescending(i => i.Id).LastOrDefault();
            return role.RoleId;
        }

        public async Task<UserRole> SaveUserRole(long userId, long roleId)
        {
            var userRole = new UserRole(userId,roleId);
            var model = new UserRole();
            var userList = await Query(i=>i.UserId==userId&&i.RoleId==roleId);
            if (userList.Count > 0)
            {
                model = userList.FirstOrDefault();
            }
            else
            {
                var id = await Add(userRole);
                model = await QueryById(id);
            }

            return model;
        }
    }
}
